package com.alstudio.net.protocol.xmpp.parser.presence;

import java.io.IOException;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParserException;

import com.alstudio.net.protocol.xmpp.XmppListener;
import com.alstudio.net.protocol.xmpp.packact.Presence;
import com.alstudio.net.protocol.xmpp.parser.BaseParser;
import com.alstudio.utils.log.Mylog;
import com.alstudio.utils.xml.BaseXmlParser;
import com.alstudio.utils.xml.BaseXmlParser.XmlParseCallback;

public class PresenceParser extends BaseParser implements XmlParseCallback {

	private Presence presence;
	private PresenceXmlParser mParser;

	public PresenceParser(Presence presence, String stream,
			XmppListener listener) {
		// TODO Auto-generated constructor stub
		this.stream = stream;
		this.presence = null;
		this.presence = presence;
		mListener = listener;
		try {
			mParser = new PresenceXmlParser(stream, this);
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void startParsePresence() {
		Mylog.d("start parsing presence...");
		try {
			mParser.start();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Mylog.d("presence parse done!");
	}

	protected class PresenceXmlParser extends BaseXmlParser {

		protected PresenceXmlParser(String xml, XmlParseCallback callback)
				throws XmlPullParserException {
			// TODO Auto-generated constructor stub
			createParser(xml);
			setXmlParseCallback(callback);
		}

		protected void start() throws XmlPullParserException, IOException {
			startParse();
		}

	}

	@Override
	public void onTagStart(String tag) {

		// TODO Auto-generated method stub
		Mylog.d("节点开始了: " + tag);

		ArrayList<String> atts = new ArrayList<String>();
		try {
			atts = mParser.getAttributes(tag);
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		for (String s : atts) {
			Mylog.e("属性有: " + s + " value为: " + mParser.getAttValue(s));
		}

	}

	@Override
	public void onTagEnd(String tag) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDocumentStart() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onDocumentEnd() {
		// TODO Auto-generated method stub
		onCallback();
	}
	
	private void onCallback(){
		if(mListener != null){
			switch(presence.getType()){
			case available:
				mListener.onJxaStatusEvent(presence.getFrom(), "online");
				break;
			default:
				break;
			}
		}
		mParser = null;
		this.presence = null;
	}

}
